import requests
import json
import time

##cron: 24 8,12,18,22 * * *
##new Env("快手系列餐补")

# ======================= 青龙通知模块 =======================
try:
    from notify import send as notify_send
    QL_NOTIFY_AVAILABLE = True
except ImportError:
    QL_NOTIFY_AVAILABLE = False
    print("未检测到青龙通知模块，将使用控制台输出")

def send_notification(title, content):
    """
    发送通知的统一接口
    :param title: 通知标题
    :param content: 通知内容
    """
    # 构建完整的通知消息
    message = f"{title}\n\n{content}"
    
    # 控制台输出
    print(f"\n{'='*50}")
    print(f"通知标题: {title}")
    print(f"通知内容:\n{content}")
    print('='*50)
    
    # 如果青龙通知可用则发送
    if QL_NOTIFY_AVAILABLE:
        try:
            notify_send(title, content)
            print("已通过青龙通知模块发送消息")
        except Exception as e:
            print(f"青龙通知发送失败: {str(e)}")
    else:
        print("未配置青龙通知，仅在控制台显示")

# ======================= 快手功能模块 =======================
def kuaishou_request(ns_sig, cookies, headers, platform_name):
    """
    通用快手请求函数
    :param ns_sig: URL中的NS_sig参数
    :param cookies: 请求使用的cookies字典
    :param headers: 请求头
    :param platform_name: 平台名称
    :return: 解析后的结果字典
    """
    url = f"https://encourage.kuaishou.com/rest/wd/encourage/unionTask/dish/report?__NS_sig4={ns_sig}&sigCatVer=1"
    data = "{}"
    
    result = {
        "platform": platform_name,
        "success": False,
        "amount": 0,
        "title": "",
        "error": "",
        "response_time": 0,
        "raw_response": ""  # 新增字段存储原始响应
    }
    
    try:
        start_time = time.time()
        res = requests.post(url, headers=headers, cookies=cookies, data=data, timeout=10)
        response_time = time.time() - start_time
        result["response_time"] = response_time
        result["raw_response"] = res.text[:500]  # 存储部分原始响应
        
        if res.status_code == 200:
            try:
                response_data = res.json()
                
                # 检查result状态码
                if response_data.get("result") != 1:
                    result["error"] = f"API返回错误状态码: {response_data.get('result', '未知')}"
                    return result
                
                # 解析data字段
                if "data" in response_data:
                    data_field = response_data["data"]
                    result["success"] = True
                    result["title"] = data_field.get("title", "无标题信息")
                    result["amount"] = data_field.get("amount", 0)
                    
                    # 检查是否有奖励信息
                    award_info = data_field.get("eventTrackingAwardInfo", {}).get("awardInfo", [])
                    if award_info:
                        result["amount"] = award_info[0].get("amount", 0)
                else:
                    result["error"] = f"响应缺少data字段"
                    
            except json.JSONDecodeError:
                result["error"] = f"无效的JSON响应"
        else:
            result["error"] = f"HTTP错误: {res.status_code}"
            
    except requests.exceptions.RequestException as e:
        result["error"] = f"请求异常: {str(e)}"
    
    return result

def format_notification_content(results):
    """
    格式化通知内容
    :param results: 所有任务的结果列表
    :return: (标题, 内容)
    """
    # 计算总金币和成功数量
    total_amount = 0
    success_count = 0
    error_messages = []
    
    # 构建各平台结果详情
    details = []
    for result in results:
        if result['success']:
            details.append(f"✅ {result['platform']}: 成功获得 {result['amount']}金币")
            total_amount += result['amount']
            success_count += 1
        else:
            error_msg = f"{result['error']}"
            # 如果错误信息过短，添加原始响应信息
            if len(error_msg) < 30 and result['raw_response']:
                error_msg += f"\n   原始响应: {result['raw_response']}"
            details.append(f"❌ {result['platform']}: {error_msg}")
            error_messages.append(f"{result['platform']}失败: {result['error']}")
    
    # 构建通知标题
    if success_count == len(results):
        title = "🎉 快手餐补任务全部成功"
    elif success_count > 0:
        title = "⚠️ 快手餐补任务部分成功"
    else:
        title = "❌ 快手餐补任务全部失败"
    
    # 添加时间信息
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    time_info = f"⏰ 执行时间: {current_time}"
    
    # 添加汇总信息
    summary = f"\n📊 任务汇总: {success_count}成功/{len(results)}任务 | 总金币: {total_amount}"
    
    # 如果有错误，添加错误信息
    error_section = ""
    if error_messages:
        error_section = "\n\n❌ 错误信息:\n" + "\n".join([f"- {msg}" for msg in error_messages])
    
    # 构建完整通知内容
    content = "\n".join([
        time_info,
        "\n📋 任务详情:",
        *details,
        summary,
        error_section
    ])
    
    return title, content

def main():
    print("开始执行快手餐补任务...")
    
    # ========== 快手饭补参数 ==========
    fanbu_ns_sig = "HUDR_sFnX-HFuAE5VsdPNKlLOPr4ntwVLcugxjxZz8_z61EHYFY07AGiHwMelb_ny_pMHxR_0BjgEKKQba1Uc3eSWmMYZtd0w8l4XDj-3MCjD__Ta43vZSJ4TCB8KqqVKMgRgdptyHjC4q5WxqzlivWeuKUH73Q5s2-4u88UkwHrtgNYFpaoTLyzpjhJN-kWm8EpIT1cd-4gSarv9lyc5eoynpqIeL1p8oDC_aNVs06Epr9SfE-VVD8DGNPFvVFjON1XAnXDeAOgpgmSP1YpdOy1ma50UexnezeIQzxW91S59Nig74-a-EOa97KCniaiQdSzvx6DbVvQlQ4O9ZB3FHGMRsAPwfpaekre0Ra5-_MMxO_S1K5imvzg8hzW00xtV2EkBfJjCVP845JNtZHhkp5-YZhboi-z-m7n_6fPBjOLINIt3Y8tVfFYUzTyVqRydZeTwh5ckgKW0moc1WndwyJqoqIh222uMxhDr_q2L_eyoTguS65h4-eB8aDmbuEH0jewPNcrsCfeIHFlC$HE_4b541fe2abc91cbf90970171970c0e37c801070200376600000016da70b83524bf9097019b563eda7b563eb100"
    
    fanbu_cookies = {
        "kpn": "KUAISHOU",
        "kpf": "ANDROID_PHONE",
        "userId": "3646221777",
        "did": "ANDROID_54e1e7815cba7486",
        "c": "XIAOMI_YZ_2023",
        "ver": "12.8",
        "appver": "12.8.40.38625",
        "language": "zh-cn",
        "countryCode": "CN",
        "sys": "ANDROID_14",
        "mod": "Xiaomi%2823127PN0CC%29",
        "net": "UNKNOWN",
        "deviceName": "Xiaomi%2823127PN0CC%29",
        "earphoneMode": "1",
        "isp": "CTCC",
        "ud": "3646221777",
        "did_tag": "0",
        "kcv": "1599",
        "app": "0",
        "bottom_navigation": "false",
        "android_os": "0",
        "oDid": "ANDROID_f20f4db9dfb8c831",
        "boardPlatform": "pineapple",
        "newOc": "XIAOMI",
        "androidApiLevel": "34",
        "slh": "0",
        "country_code": "cn",
        "hotfix_ver": "",
        "did_gt": "1728391080409",
        "cdid_tag": "2",
        "max_memory": "256",
        "oc": "XIAOMI_YZ_2023",
        "sh": "2670",
        "deviceBit": "0",
        "browseType": "4",
        "socName": "Qualcomm+Snapdragon+8650",
        "is_background": "0",
        "sw": "1200",
        "ftt": "bd-T-T",
        "abi": "arm64",
        "cl": "0",
        "userRecoBit": "0",
        "device_abi": "arm64",
        "icaver": "1",
        "totalMemory": "15207",
        "grant_browse_type": "AUTHORIZED",
        "iuid": "",
        "rdid": "ANDROID_044c2ac124c22ec6",
        "sbh": "116",
        "darkMode": "false",
        "token": "0c582c3552c84408ae21d11d7be7d63c-3646221777",
        "__NSWJ": "",
        "client_key": "3c2cd3f3",
        "nbh": "46",
        "ddpi": "457",
        "egid": "DFPC3AB78BFF171FD8038E441947A9D449CA11184A8AFA6BC84BA076E5BA5153",
        "thermal": "10000",
        "kuaishou.api_st": "Cg9rdWFpc2hvdS5hcGkuc3QSoAEPnSMeapDKv7OrRTCaqHPkoIecSSAANfqDOIL4t0pP-x9zNJztJcxgpA7w8Y3eps-z_UEPRh753vlVECVtGWsOUaPgMJ9Alio3hc89NvsDyNV3riz9MW93auAXqE8GVPYLM5JcvoGnz2h_Hg9xX8n7qzXedJXyWODCd9ELloF7jjK6nD5YMAKGh9nmGmsCyL0uNTFtvoO6V3sAfu8KaCrYGhKBn81trpJKB6BrmlxeXw7Wm2EiIDQYG3Z7nOLcVUeRBnqvUjf2Vf5w1ijqsxT6d2qhIWtKKAUwAQ",
        "kuaishou.h5_st": "Cg6rdWFpc2hvdS5oNS5zdBKgASSnx90d-h4GCc5d2Jya3bAL_pceIrikHn5HdJteet7EGeyrCa1ywcJeCnQnxoF4O50CPguicALoh-Sia6BSr2qvPINmI4-JoW1cndwV6m1zqYJbN9tV-gLnxsvCGBNWrhx2PnKNYCQi8FEJdiA1fL26yt5UA40LXX4JjvFLt78AfV46kQp3isZLouaVrDyl7dnC-7DruT0Oo7_AAUPXsKQaEr7HkeXUKLsZtMH-j4EHZjUlyCIg063LwJRj1AFW2HLh4y57mtvSoYNVkTFqbsFozaMSC9soBTAB",
        "sid": "59d7c477-ea85-4f90-9c6c-5afb73406262",
        "cold_launch_time_ms": "1750479841639",
        "keyconfig_state": "2",
    }
    
    fanbu_headers = {
        "Host": "encourage.kuaishou.com",
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.226 KsWebView/1.8.90.728 (rel) Mobile Safari/537.36 Yoda/3.1.9-rc1 Kwai/12.8.40.38625 OS_PRO_BIT/64 MAX_PHY_MEM/15207 KDT/PHONE AZPREFIX/az2 ICFO/0 StatusHT/40 TitleHT/43 NetType/WIFI ISLP/0 ISDM/0 ISLB/0 locale/zh-cn DPS/17.148 DPP/94 SHP/2554 SWP/1200 SD/2.85625 CT/0 ISLM/0",
        "content-type": "application/json",
        "Accept": "*/*",
        "Origin": "https://encourage.kuaishou.com",
        "X-Requested-With": "com.smile.gifmaker",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://encourage.kuaishou.com/activity/dish?layoutType=4&encourageTaskValidityTrack=eyJhY3Rpdml0eV9pZCI6MjAwMDgsInJlc291cmNlX2lkIjoiZWFyblBhZ2VfdGFza0xpc3RfNSIsImV4dF9wYXJhbXMiOnsiaXNTZXJ2ZXJSZWNvcmRDbGlja0FjdGlvbiI6dHJ1ZX19&encourageEventTracking=W3siZW5jb3VyYWdlX3Rhc2tfaWQiOjIwMDA4LCJlbmNvdXJhZ2VfcmVzb3VyY2VfaWQiOiJlYXJuUGFnZV90YXNrTGlzdF81IiwiZXZlbnRUcmFja2luZ0xvZ0luZm8iOlt7ImRlbGl2ZXJPcmRlcklkIjoiNDM3IiwibWF0ZXJpYWxLZXkiOiJUQVNLX0xJU1RfMjAwMDhfRElTSF9TVUJTSURZX0FWQUlMQUJMRSIsImV2ZW50VHJhY2tpbmdUYXNrSWQiOjIwMDA4LCJyZXNvdXJjZUlkIjoiZWFyblBhZ2VfdGFza0xpc3RfNSIsImV4dFBhcmFtcyI6eyJpc1NlcnZlclJlY29yZENsaWNrQWN0aW9uIjp0cnVlfX1dfV0",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    
    # ========== 快手极速版参数 ==========
    jisuban_ns_sig = "HUDR_sFnX-HFuAE5VsdPNKlLOPr4ntwVLcugxjxZz8_z61EHYFY07AGiHwMelb_ny_pMHxR_0BjgEKKQba1Uc3eSWmMYZtd0w8l4XDj-3MCjD__Ta43vZSJ4TCB8KqqVKMgRgdptyHjC4q5WxqzlivWeuPEH73Q5s2-4u88UkwHrtgNYFpaoTLyzpjhJN-kWm8EpIT1cd-4gSarv9lyc5eoynpqIeL1p8oDC_aNVs06Epr9SfE-VVD8DGNPFvVFjON1XAnXDeAOgpgmSP1YpdOy1ma50UexnezeIQzxW91S59Nig74-a-EOa97KCniaiQdSzvx6DbVvQlQ4O9ZB3FHGMRsAPwfpaekre0Ra5-gsMxO_S1K5imvzg8hzW00xtV2EkBfJjCVP845JNtZHhkp5-YZhboi-z-m7n_6fPBjOLINIt3Y8tVfFYUzTyVqRydZeTwh5ckgKW0moc1WndwyJqoqIh222uMxhDr_q2L_eyoTguS65h4-eB8aDmbuEH0jewPNcrsCfeIHFlC$HE_4b541fe2abcf5fb39097015ba817e790a70107020037660000001b8d72e67d68b39097019b563eda7b563ef500"
    
    jisuban_cookies = {
        "kpn": "NEBULA",
        "kpf": "ANDROID_PHONE",
        "userId": "3646221777",
        "did": "ANDROID_54e1e7815cba7486",
        "c": "XIAOMI",
        "ver": "12.0",
        "appver": "12.0.40.7282",
        "language": "zh-cn",
        "countryCode": "CN",
        "sys": "ANDROID_14",
        "mod": "Xiaomi%2823127PN0CC%29",
        "net": "WIFI",
        "deviceName": "Xiaomi%2823127PN0CC%29",
        "earphoneMode": "1",
        "isp": "CTCC",
        "ud": "3646221777",
        "did_tag": "0",
        "egid": "DFPB526D31065E5CC7AA06EC47D0B3294334B28AEFF4B6CCA272E52F84ADB441",
        "thermal": "10000",
        "kcv": "1599",
        "app": "0",
        "bottom_navigation": "true",
        "android_os": "0",
        "oDid": "ANDROID_f20f4db9dfb8c831",
        "boardPlatform": "pineapple",
        "newOc": "XIAOMI",
        "androidApiLevel": "34",
        "slh": "0",
        "country_code": "cn",
        "nbh": "46",
        "hotfix_ver": "",
        "did_gt": "1723694814615",
        "keyconfig_state": "2",
        "cdid_tag": "2",
        "max_memory": "256",
        "oc": "XIAOMI",
        "sh": "2670",
        "deviceBit": "0",
        "browseType": "3",
        "ddpi": "457",
        "socName": "Qualcomm+Snapdragon+8650",
        "is_background": "0",
        "sw": "1200",
        "ftt": "bd-T-T",
        "apptype": "22",
        "abi": "arm64",
        "cl": "0",
        "userRecoBit": "0",
        "device_abi": "arm64",
        "totalMemory": "15207",
        "grant_browse_type": "AUTHORIZED",
        "iuid": "",
        "rdid": "ANDROID_66076269c9559a4d",
        "sbh": "116",
        "darkMode": "false",
        "kuaishou.api_st": "Cg9rdWFpc2hvdS5hcGkuc3QSoAGLS0nXMljL2yYaNA_3f-hP3zs3lLhNnvFztXh8cuPOYBtx_wh0jGFVA4pEDA_0RkQJPKZEmEG2Wx29klEq4rCIpsLHmXlZDr8sjHsrCkuZSLi5wO7QAtoKid-_86GSRH6u2wXeJ1RnS5MMeQSI10gAnRgbfb8IOTpux3HZd4IA0Kg4BQZfEDyt8_QGHzRVq3uTl-THqUcMqO6lPemuoFYcGhI7XTEVdHBIipx6QeDcmp0mlFciIBhWAwKN4TlBOlYI443CUycnrwj-9rQ22XYQphJKXl9vKAUwAQ",
        "token": "Cg9rdWFpc2hvdS5hcGkuc3QSoAGLS0nXMljL2yYaNA_3f-hP3zs3lLhNnvFztXh8cuPOYBtx_wh0jGFVA4pEDA_0RkQJPKZEmEG2Wx29klEq4rCIpsLHmXlZDr8sjHsrCkuZSLi5wO7QAtoKid-_86GSRH6u2wXeJ1RnS5MMeQSI10gAnRgbfb8IOTpux3HZd4IA0Kg4BQZfEDyt8_QGHzRVq3uTl-THqUcMqO6lPemuoFYcGhI7XTEVdHBIipx6QeDcmp0mlFciIBhWAwKN4TlBOlYI443CUycnrwj-9rQ22XYQphJKXl9vKAUwAQ",
        "__NSWJ": "",
        "client_key": "2ac2a76d",
        "kuaishou.h5_st": "Cg6rdWFpc2hvdS5oNS5zdBKgAedBwaWNpNaH3NbwMYytSB1rGcINDiEivg5uMXOpzleWCE_REaLHhG6nhklPAlNq-F4Dxwcmy5Ul7zWUvehpxp764c6Aol4wA-kLIWVTWH2523x6gfZ3OYkOXkabe3ICTu-P9oGm1B0FeZeXSvg7djF3s61MUKhAmHPXBKPEmWm3t8NM_mZ8wOlMr8awr0h9TKfz07Yt51Pjk5FITcv0dD4aEqWAqa4qaXGcL-RKnK6eSUQY8iIg9dFgfld7d83pCWe8Ckt5inBvv7vkFIxS9HOytCDrE4ooBTAB",
        "sid": "e26accc9-d026-48f5-9498-aa1738f8ffd5",
        "cold_launch_time_ms": "1750479343169",
    }
    
    jisuban_headers = {
        "Host": "encourage.kuaishou.com",
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.226 KsWebView/1.8.90.671 (rel) Mobile Safari/537.36 Yoda/3.1.7-alpha26 ksNebula/12.0.40.7282 OS_PRO_BIT/64 MAX_PHY_MEM/15207 AZPREFIX/az2 ICFO/0 StatusHT/40 TitleHT/43 NetType/WIFI ISLP/0 ISDM/0 ISLB/0 locale/zh-cn DPS/17.148 DPP/95 CT/0 ISLM/0",
        "content-type": "application/json",
        "Accept": "*/*",
        "Origin": "https://encourage.kuaishou.com",
        "X-Requested-With": "com.kuaishou.nebula",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://encourage.kuaishou.com/activity/dish?layoutType=4&encourageTaskValidityTrack=eyJhY3Rpdml0eV9pZCI6MjAwMDgsInJlc291cmNlX2lkIjoiZWFyblBhZ2VfdGFza0xpc3RfNSIsImV4dF9wYXJhbXMiOnsiaXNTZXJ2ZXJSZWNvcmRDbGlja0FjdGlvbiI6dHJ1ZX19&encourageEventTracking=W3siZW5jb3VyYWdlX3Rhc2tfaWQiOjIwMDA4LCJlbmNvdXJhZ2VfcmVzb3VyY2VfaWQiOiJlYXJuUGFnZV90YXNrTGlzdF81IiwiZXZlbnRUcmFja2luZ0xvZ0luZm8iOlt7ImRlbGl2ZXJPcmRlcklkIjoiMjIyIiwibWF0ZXJpYWxLZXkiOiJUQVNLX0xJU1RfMjAwMDhfRElTSF9TVUJTSURZX0FWQUlMQUJMRSIsImV2ZW50VHJhY2tpbmdUYXNrSWQiOjIwMDA4LCJyZXNvdXJjZUlkIjoiZWFyblBhZ2VfdGFza0xpc3RfNSIsImV4dFBhcmFtcyI6eyJpc1NlcnZlclJlY29yZENsaWNrQWN0aW9uIjp0cnVlfX1dfV0",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    
    # 存储所有任务结果
    all_results = []
    
    # 执行饭补请求
    print("\n" + "="*30 + " 开始执行快手饭补 " + "="*30)
    fanbu_result = kuaishou_request(
        fanbu_ns_sig, 
        fanbu_cookies, 
        fanbu_headers, 
        "快手饭补"
    )
    all_results.append(fanbu_result)
    
    # 打印结果
    print(f"\n平台: {fanbu_result['platform']}")
    print(f"响应时间: {fanbu_result['response_time']:.2f}秒")
    if fanbu_result['success']:
        print(f"状态: 成功 ✅")
        print(f"标题: {fanbu_result['title']}")
        print(f"获得金额: {fanbu_result['amount']}金币")
    else:
        print(f"状态: 失败 ❌")
        print(f"错误信息: {fanbu_result['error']}")
        if fanbu_result['raw_response']:
            print(f"原始响应: {fanbu_result['raw_response']}")
    print('='*40)
    
    # 执行极速版请求
    time.sleep(1)  # 避免请求过快
    print("\n" + "="*30 + " 开始执行快手极速版 " + "="*30)
    jisuban_result = kuaishou_request(
        jisuban_ns_sig, 
        jisuban_cookies, 
        jisuban_headers, 
        "快手极速版"
    )
    all_results.append(jisuban_result)
    
    # 打印结果
    print(f"\n平台: {jisuban_result['platform']}")
    print(f"响应时间: {jisuban_result['response_time']:.2f}秒")
    if jisuban_result['success']:
        print(f"状态: 成功 ✅")
        print(f"标题: {jisuban_result['title']}")
        print(f"获得金额: {jisuban_result['amount']}金币")
    else:
        print(f"状态: 失败 ❌")
        print(f"错误信息: {jisuban_result['error']}")
        if jisuban_result['raw_response']:
            print(f"原始响应: {jisuban_result['raw_response']}")
    print('='*40)
    
    # 生成并发送通知
    title, content = format_notification_content(all_results)
    send_notification(title, content)
    
    # 计算总金币
    total_amount = 0
    for result in all_results:
        if result['success']:
            total_amount += result['amount']
    
    print(f"\n💰 总获得金币: {total_amount}金币")
    print(f"⏰ 执行完成时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}")

if __name__ == "__main__":
    main()